import React from 'react';
import { Modal, Form, Input, Select, message } from 'antd';
import _ from 'lodash';

import { ReportType, ReportFile } from '../core/common'
import SparkChannel from '../ipc/sparkchannel'

/**
    [
        {
          value: 1,
          label: '日报表',
        },
        {
          value: 2,
          label: '周报表',
        }
    ]
 */

class ReportFileDialog extends React.Component {
  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleAfterClose = this.handleAfterClose.bind(this);
    this.onFinish = this.onFinish.bind(this);
    this.onFinishFailed = this.onFinishFailed.bind(this);

    this.formRef = React.createRef();
    this.state = { confirmLoading: false }

    const typeOptions = ReportType.options();
    this.state = { typeOptions }
  }

  handleSubmit() {
    this.formRef.current.submit();
  }
  handleAfterClose() {
    this.formRef.current.resetFields();
  }

  async onFinish(values) {
    console.log('Success:', values);
    const directory_id = values.directory;
    const report_type = parseInt(values.report_type);
    let report_name = values.filename;
    // if (!_.endsWith(fileName, REPORT_TPL_SUFFIX)) {
    //     fileName = fileName + REPORT_TPL_SUFFIX;
    // }

    this.setState({ confirmLoading: true });
    if (this.props.edit) {
      const report = this.props.report;
      try {
        const channel = await SparkChannel();
        let resp = await channel.request_update_report({
          ...report,
          directory_id, report_type, report_name
        });
        this.props.onFileSaved(this.props.edit, resp);
      } catch (err) {
        console.log('update report fail', err)
        message.error('修改文件失败');
      }
    } else {
      try {
        const channel = await SparkChannel();
        let resp = await channel.request_insert_report({
          directory_id, report_type, report_name
        });

        const report = resp.data.report;
        const content = ReportFile.defaultFileContent(report);
        await ReportFile.writeContent(report, content);

        this.props.onFileSaved(this.props.edit, resp);
      } catch (err) {
        console.log('create report fail', err)
        message.error('创建文件失败');
      }
    }
    this.setState({ confirmLoading: false });
  };
  onFinishFailed(errorInfo) {
    console.log('Failed:', errorInfo);
  };

  render() {
    const { edit, open, onCancel } = this.props;
    const directorys = this.props.directorys.map(catalog => {
      return {
        value: catalog.id,
        label: catalog.directory_name,
      };
    });
    const initialValues = {};
    const report = this.props.report;
    if (!_.isNil(report.directory_id)) {
      initialValues.directory = report.directory_id;
    } else if (!_.isEmpty(directorys)) {
      initialValues.directory = directorys[0].value;
    }
    initialValues.report_type = _.isNil(report.report_type) ? 1 : report.report_type;
    initialValues.filename = report.report_name;

    return (
      <Modal title={edit ? "编辑报表" : "新建报表"}
        zIndex={1020}
        open={open} confirmLoading={this.state.confirmLoading}
        onCancel={onCancel}
        onOk={this.handleSubmit}
        afterClose={this.handleAfterClose}>
        <Form
          colon={false}
          ref={this.formRef}
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          initialValues={initialValues}>
          <Form.Item
            label="存储目录"
            name="directory"
            rules={[
              {
                required: true,
              },
            ]}>
            <Select options={directorys} />
          </Form.Item>
          <Form.Item
            label="报表类型"
            name="report_type"
            rules={[
              {
                required: true,
              },
            ]}>
            <Select options={this.state.typeOptions} disabled={edit} />
          </Form.Item>

          <Form.Item
            label="文件名称"
            name="filename"
            rules={[
              {
                required: true,
                // message: '请输入文件名称!',
              },
            ]}
          >
            <Input type="text" />
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default ReportFileDialog